package com.lin.sqltool.utils;



import com.lin.sqltool.beans.BaseBean;
import com.lin.sqltool.model.ConnectionInfoModel;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.lin.sqltool.config.BaseConfig.CONNECTIONS_FILE;
import static com.lin.sqltool.config.BaseConfig.SAVE_DIR;

public class ConnectionUtil {


    /**
     * 连接集合
     */
    private static final List<ConnectionInfoModel> CONNECTIONS = new ArrayList<>();





    /**
     * 标志位，记录是否已经加载过连接配置
     */
    private static boolean isConnectionsLoaded = false;



    /**
     * 新增连接
     *
     * @param connectionModel
     * @return
     */
    public static boolean addConnection(ConnectionInfoModel connectionModel) {
        CONNECTIONS.add(connectionModel);
        return saveConnections();
    }

    /**
     * 删除连接
     *
     * @param name
     * @return
     */
    public static boolean deleteConnection(String name) {
        boolean removed = CONNECTIONS.removeIf(conn -> conn.getName().equals(name));
        if (removed) {
            return saveConnections();
        }
        return false;
    }

    public static boolean renameConnection(String currentName, String newName) {
        ConnectionInfoModel model = getConnectionByName(currentName);
        if (model==null) {
            return false;
        }
        model.setName(newName);
        return saveConnections();
    }

    public static ConnectionInfoModel getConnectionByName(String name) {
        return CONNECTIONS.stream()
                .filter(conn -> conn.getName().equals(name))
                .findFirst()
                .orElse(null);
    }


    /**
     * 修改连接
     *
     * @param connectionModel
     * @return
     */
    public static boolean saveConnection(ConnectionInfoModel connectionModel) {
        ConnectionInfoModel old = getConnectionByName(connectionModel.getName());
        if (old == null) {
            addConnection(connectionModel);
        }
        old.setName(connectionModel.getName());
        old.setHost(connectionModel.getHost());
        old.setPort(connectionModel.getPort());
        old.setDatabaseType(connectionModel.getDatabaseType());
        old.setPassword(connectionModel.getPassword());
        old.setUsername(connectionModel.getUsername());
        return saveConnections();
    }


    /**
     * 获取全部连接
     *
     * @return
     */
    public static List<ConnectionInfoModel> getConnections() {
        if (!isConnectionsLoaded) {
            loadConnections();
        }
        if (CONNECTIONS.isEmpty()) {
            CONNECTIONS.add(new ConnectionInfoModel("新连接","localhost","3306","root","","mysql"));
            saveConnections();
        }
        return new ArrayList<>(CONNECTIONS);
    }

    /**
     * 根据类型获取全部名称
     * @return
     */
    public static List<String> getConnectionsNames() {
        return getConnections().stream().map(ConnectionInfoModel::getName).collect(Collectors.toList());
    }


    /**
     * 保存连接到文件
     * @return
     */
    public static boolean saveConnections(){

        try {
            Files.createDirectories(SAVE_DIR);
            BaseBean.objectMapper.writeValue(CONNECTIONS_FILE.toFile(), CONNECTIONS);
            return true;
        } catch (IOException e) {
            System.err.println("保存连接配置失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 加载连接
     * @return
     */
    public static boolean loadConnections() {

        try {
            if (CONNECTIONS_FILE.toFile().exists()) {
                // 反序列化为 List<ConnectionModel>
                List<ConnectionInfoModel> connectionModels = BaseBean.objectMapper.readValue(
                        CONNECTIONS_FILE.toFile(),
                        BaseBean.objectMapper.getTypeFactory().constructCollectionType(List.class, ConnectionInfoModel.class)
                );
                // 直接设置到 ObservableList
                CONNECTIONS.addAll(connectionModels);
                isConnectionsLoaded = true;
                return true;
            }

        } catch (IOException e) {
            System.err.println("加载连接配置失败: " + e.getMessage());

        }
        return false;
    }




}
